import React, { useState, useRef, useEffect } from 'react';
import { Input, Button, List, Avatar, Typography, Space, message } from 'antd';
import { SendOutlined, UserOutlined, RobotOutlined } from '@ant-design/icons';
import { ChatMessage } from '../types';
import { chatMessagesApi } from '../utils/supabase';

const { TextArea } = Input;
const { Text } = Typography;

const ChatSidebar: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      id: '1',
      type: 'ai',
      content: '你好！我是地图助手，我可以帮您在地图上标记位置、规划路线等。请问有什么可以帮助您的？',
      timestamp: new Date().toISOString(),
    },
  ]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // Mock AI 响应函数
  const getMockAIResponse = (userInput: string): string => {
    const lowerInput = userInput.toLowerCase();
    
    if (lowerInput.includes('你好') || lowerInput.includes('hello')) {
      return '你好！我是地图AI助手，我可以帮你在地图上添加标记点、规划路线等。请告诉我你想做什么。';
    } else if (lowerInput.includes('标记') || lowerInput.includes('点') || lowerInput.includes('位置')) {
      return '我理解你想添加地图标记。请点击地图上的任意位置来添加标记点，然后我可以帮你保存它。';
    } else if (lowerInput.includes('路线') || lowerInput.includes('导航')) {
      return '路线规划功能正在开发中。目前你可以通过点击地图添加多个标记点来模拟路线。';
    } else if (lowerInput.includes('咖啡') || lowerInput.includes('餐厅')) {
      return '我可以帮你查找附近的咖啡店或餐厅。请先点击地图设置一个中心位置。';
    } else if (lowerInput.includes('帮助')) {
      return '我可以帮你：\n1. 添加地图标记点\n2. 模拟路线规划\n3. 回答位置相关问题\n请尝试点击地图或输入具体指令。';
    } else {
      return `我收到了你的请求："${userInput}"。这是一个模拟AI响应，实际版本会集成真实的AI API来理解并执行你的地图操作指令。`;
    }
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      type: 'user',
      content: inputValue,
      timestamp: new Date().toISOString(),
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setLoading(true);

    try {
      // 保存用户消息到Supabase
      await chatMessagesApi.addMessage(userMessage);

      // 模拟AI响应
      setTimeout(async () => {
        const aiResponseContent = getMockAIResponse(inputValue);
        const aiMessage: ChatMessage = {
          id: (Date.now() + 1).toString(),
          type: 'ai',
          content: aiResponseContent,
          timestamp: new Date().toISOString(),
        };

        // 保存AI响应到Supabase
        await chatMessagesApi.addMessage(aiMessage);
        setMessages(prev => [...prev, aiMessage]);
        setLoading(false);
      }, 800);
    } catch (error) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败，请检查网络连接或Supabase配置');
      setLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
      {/* 聊天标题 */}
      <div style={{ 
        padding: '16px', 
        borderBottom: '1px solid #d9d9d9',
        background: '#fafafa'
      }}>
        <Space>
          <RobotOutlined style={{ color: '#1890ff' }} />
          <Text strong>地图 AI 助手</Text>
        </Space>
      </div>

      {/* 消息列表 */}
      <div style={{ 
        flex: 1, 
        overflow: 'auto', 
        padding: '16px',
        background: '#f5f5f5'
      }}>
        <List
          dataSource={messages}
          renderItem={(message) => (
            <List.Item style={{ 
              border: 'none', 
              padding: '8px 0',
              display: 'flex',
              flexDirection: message.type === 'user' ? 'row-reverse' : 'row'
            }}>
              <Space align="start" style={{ maxWidth: '85%' }}>
                <Avatar 
                  icon={message.type === 'user' ? <UserOutlined /> : <RobotOutlined />}
                  style={{ 
                    background: message.type === 'user' ? '#1890ff' : '#52c41a'
                  }}
                />
                <div style={{ 
                  background: message.type === 'user' ? '#1890ff' : '#fff',
                  color: message.type === 'user' ? '#fff' : '#000',
                  padding: '8px 12px',
                  borderRadius: '12px',
                  boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
                }}>
                  <Text style={{ color: message.type === 'user' ? '#fff' : 'inherit' }}>
                    {message.content}
                  </Text>
                  <div style={{ 
                    fontSize: '12px', 
                    opacity: 0.7, 
                    marginTop: '4px',
                    textAlign: message.type === 'user' ? 'right' : 'left'
                  }}>
                    {new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
                      hour: '2-digit', 
                      minute: '2-digit' 
                    })}
                  </div>
                </div>
              </Space>
            </List.Item>
          )}
        />
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div style={{ 
        padding: '16px', 
        borderTop: '1px solid #d9d9d9',
        background: '#fff'
      }}>
        <Space.Compact style={{ width: '100%' }}>
          <TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入您的地图操作指令..."
            autoSize={{ minRows: 1, maxRows: 4 }}
            style={{ resize: 'none' }}
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSendMessage}
            loading={loading}
            style={{ height: 'auto' }}
          >
            发送
          </Button>
        </Space.Compact>
      </div>
    </div>
  );
};

export default ChatSidebar;